<?php
/***************************************************************
 *  Copyright notice
 *
 *  (c) 2007-2008 Starbugs (univis2typo3@googlegroups.com)
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *  A copy is found in the textfile GPL.txt and important notices to the license
 *  from the author is found in LICENSE.txt distributed with these scripts.
 *
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/
/**
 * Module: Web>UnivIS2Typo3
 *
 * Description:
 * 	Fill the tx_u2t3_XX with content from it's u_XX-counterpart
 * 	for EVERY key there will be a lookup into tx_u2t3_uid_key to check if
 * 	it's already set. The UID _must_ be fix because typo3 refers to it.
 *
 * Notice: 
 *
 *  
 * @author	Johannes Held <univis2typo3@googlegroups.com>
 */

 require_once(t3lib_extMgm::extPath('univis2typo3').'/mod1/parser/class.parser.php');
 require_once(t3lib_extMgm::extPath('univis2typo3').'/mod1/parser/debug.php');
 require_once(t3lib_extMgm::extPath('univis2typo3').'/mod1/parser/error.php');


 global $DEBUG_MODE, $ERROR_MODE;
 $DEBUG_MODE = false;
 $ERROR_MODE = true;

 class FillTXTables {
	private $key2uid = array();


	// the tables to copy & the name of the key_attribute
	// sometimes it's "key" and sometimes "parent_key" oder "pkey" or whatever
	private $tables = array(
		'job' => array('parent_key', 'description'),
		'person' => array('key', 'firstname'),
		'title'  => array('key', 'title'),
		'research' => array('key', 'contact'),
		'room'  => array('key', 'short'),
		'lecture' => array('key', 'semester'),
		'thesis' => array('key', 'firstname'),
		'pub' => array('key', 'year'),
		'org' => array('key', 'department_id')
	);

	/* Fills the $key2uid array with it's inital values from 'tx_u2t3_uid_key'
	 */
	private function fillKey2Uid() {
		$result = $GLOBALS['TYPO3_DB']->sql_query("select * from tx_u2t3_uid_key;");	
		$cnt = 0;
	
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
			$this->key2uid[$row['key']] = $row['uid'];
			++$cnt;
		}	
		
		echo($cnt . " key,uid pairs loaded from tx_u2t3_uid_key <br />\n");
	}
	
	/* Checks the $key2uid hash for given key.
	 * If the key is present it's returned
	 * 
	 * Else an insert into tx_u2t3_uid_key is made.
	 * The new key,uid -pair will be added into key2uid and the uid is returned 
	 */
	private function getUidForKey($key1, $key2) {
	    static $lastkey = "";
	    static $lastuid = "";

	    $concat_key = $key1 . '__' . $key2;
	    // do a little bit of caching here
		if($lastkey == $concat_key)
		    return $lastuid;

		$uid = "";
		if (array_key_exists($concat_key, $this->key2uid)) {
			// <key> is already known, take the <uid> form out hash
			$uid =  $this->key2uid[$concat_key];
		}
		else {
			// <key> is new. create a new <uid> by inserting the <key> into "tx_u2t3_uid_key"
			$query = "insert into tx_u2t3_uid_key (`key`) values('{$concat_key}')";
		
			$result = $GLOBALS['TYPO3_DB']->sql_query($query);
			if(!$result) {
			    U2T3_ERROR(mysql_error() . "<br />" . $query . "<br />");
			}
				
			$stmt = "select max(uid) as muid from tx_u2t3_uid_key";
			$result = $GLOBALS['TYPO3_DB']->sql_query($stmt);
			
			if(!$result) {
			    echo(mysql_error() . "<br />" . $query . "<br />");
			}
			while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
				$uid = $row['muid'];
			}
			
			// didn't work, cause the primary key of tx_u2t3_uid_key is (uid, key)
			// and that gave us an integer made out of (integer, varchar) ...
			// $uid = mysql_insert_id();
			
			
			
			
			$this->key2uid[$concat_key] = $uid;
		}

		$lastuid = $uid;
		$lastkey = $concat_key;
		return $uid;
			
	}

	/* copyUtoTX
	 * Should be quite generic. pass the table WITHOUT "u_"
	 * I fetch a list of fields in this table and generate the insert-statement.
	 */
	private function copyUtoTX($table, $fieldname_keys) {
		$u_table = "u_".$table;
		$tx_table = "tx_u2t3_".$table;	
		$uid = "";
		$fields = array();
		$cnt = 0;
		
		$insert_head = "";
		$insert_body = "";
		
		U2T3_DEBUG("processing table " . $u_table . "<br />");
		
		// get all the fields in this table, saving only the name
		$select = "show columns from {$u_table}";
		$fieldqry_result = $GLOBALS['TYPO3_DB']->sql_query($select);
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($fieldqry_result)) {
			$fields[] = $row['Field'];
		}

		// create the first body of the insert-statement
		// insert into (uid, xxx, xxx, xxx, xxx) 
		$insert_head = "insert into {$tx_table} (uid";
		foreach($fields as $field) {
			$insert_head .= ", `{$field}`";
		}
		$insert_head .= ") ";
		
		
		$select = "select * from {$u_table}";
		$select_result = $GLOBALS['TYPO3_DB']->sql_query($select);
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($select_result)) {
		
			$uid = $this->getUidForKey($row[$fieldname_keys[0]], $row[$fieldname_keys[1]]);
			
			// create the rest of insert-statment.
			// values('xxx','xxx','xxx','xx');
			$insert_body = "values('{$uid}'";
			foreach($fields as $field) {
			    // Some values contain an "'"! So I can't use "'" for values...
			    $value = preg_replace("/'/", "\'", $row[$field]);
			    $insert_body .= ",'{$value}'";
			}
			$insert_body .= ");";
			
			// inserting the new record into database.
			// dying on error :)
			$insert_stmt = $insert_head . $insert_body;
			$insert_result = $GLOBALS['TYPO3_DB']->sql_query($insert_stmt);
			if(!$insert_result) {
			    U2T3_ERROR(mysql_error() . "<br />" . $insert_stmt . "<br />");
			}
			
			++$cnt;
		}	
		
		U2T3_DEBUG("&nbsp;&nbsp;inserted {$cnt} records from {$u_table} into {$tx_table} <br />");

	}
	
	public function copyTables() {
		foreach($this->tables as $table => $key_fields) {
			$this->copyUtoTx($table, $key_fields);
		}
	}
	
	public function __construct() {
		$this->fillKey2Uid();
	}
 
 }
 
 ?>
